package com.itic.im.spring;

import com.itic.im.core.ImManager;
import com.itic.im.core.annotation.ImMsgType;
import com.itic.im.core.handler.ImMsgHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;

import java.util.Map;

/**
 * spring容器初始化完成事件
 * Created by yangwl
 */
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextListener.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // root application context
        if (null == contextRefreshedEvent.getApplicationContext().getParent()) {
            Map<String, Object> beans = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(ImMsgType.class);
            for (Object o : beans.values()) {
                try {
                    ImMsgHandler handler = (ImMsgHandler) o;
                    AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(handler.getClass(), ImMsgType.class);
                    ImManager.setTranslator((String) attributes.get("value"), handler);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
